package com.autumn.sms.service.vo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.autumn.sms.service.SmsSendException;

/**
 * 平台模板
 * 
 * @author 老码农
 *
 *         2018-01-12 13:27:29
 */
public class PlatformTemplateValue extends AbstractSmsTemplateValue {

	/**
	 * platform_template
	 */
	private static final long serialVersionUID = 5551176780824119901L;
	private String platformCode;
	private String platformName;
	private Map<String, Object> configInfoMap;
	private String signName;
	private List<PlatformTemplateParameterValue> parameters;

	public PlatformTemplateValue() {
		this.setParameters(new ArrayList<>());
		this.setConfigInfoMap(new HashMap<>());
	}

	public String getPlatformCode() {
		return platformCode;
	}

	public void setPlatformCode(String platformCode) {
		this.platformCode = platformCode;
	}

	public String getPlatformName() {
		return platformName;
	}

	public void setPlatformName(String platformName) {
		this.platformName = platformName;
	}

	public Map<String, Object> getConfigInfoMap() {
		return configInfoMap;
	}

	public void setConfigInfoMap(Map<String, Object> configInfoMap) {
		this.configInfoMap = configInfoMap;
	}

	public String getSignName() {
		return signName;
	}

	public void setSignName(String signName) {
		this.signName = signName;
	}

	public List<PlatformTemplateParameterValue> getParameters() {
		return parameters;
	}

	public void setParameters(List<PlatformTemplateParameterValue> parameters) {
		this.parameters = parameters;
	}

	private final static String ERROR_FORMAT = "%s 的模板 %s 必须拥有参数 %s 的值。";

	/**
	 * 生成平台参数
	 * 
	 * @param requestMap
	 *            请求map
	 * @return
	 *
	 */
	public Map<String, String> generatePlatformParameter(Map<String, String> requestMap) {
		List<PlatformTemplateParameterValue> parList = getParameters();
		Map<String, String> tempMap = new HashMap<>(16);
		if (requestMap == null || parList == null || parList.size() == 0) {
			return tempMap;
		}
		// 换成大写，防止大小写转换问题
		for (Map.Entry<String, String> entry : requestMap.entrySet()) {
			if (entry.getKey() != null && entry.getValue() != null) {
				tempMap.put(entry.getKey().trim().toUpperCase(), entry.getValue());
			}
		}
		Map<String, String> result = new HashMap<>(16);
		for (PlatformTemplateParameterValue par : parList) {
			if (par.getStandardParameterName() != null) {
				String value = tempMap.get(par.getStandardParameterName().toUpperCase());
				if (value != null) {
					result.put(par.getName(), value);
				} else {
					if (par.getIsMust()) {
						throw new SmsSendException(false, false, String.format(ERROR_FORMAT, this.getPlatformName(),
								this.getTemplateCode(), par.getName()));
					}
				}
			} else {
				if (par.getIsMust()) {
					throw new SmsSendException(false, false,
							String.format(ERROR_FORMAT, this.getPlatformName(), this.getTemplateCode(), par.getName()));
				}
			}
		}
		return result;
	}
}
